package cn.czh.controller;


import cn.czh.core.AjaxResult;
import cn.czh.dao.TeacherDao;
import cn.czh.entity.Teacher;
import cn.czh.exception.BaseException;
import cn.czh.service.impl.TeacherServiceImpl;
import cn.czh.utils.BaseController;
import cn.czh.utils.StringUtils;
import cn.czh.utils.page.TableDataInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author czh
 * @since 2021-05-31
 */
@CrossOrigin(origins = "http://localhost:8080", maxAge = 3600)
@RestController
@RequestMapping("/teacher")
public class TeacherController extends BaseController {
    @Autowired
    TeacherServiceImpl teacherService;
    @Autowired
    TeacherDao teacherDao;
    @GetMapping("/list")
    public TableDataInfo findAllTeacher(Teacher teacher){
        startPage();
        List<Teacher> all = teacherService.findAll(teacher);
        return getDataTable(all);
    }

    @PostMapping
    public AjaxResult addTeacher(@RequestBody Teacher teacher){
        if(StringUtils.isNotNull(teacher))
        {
            int i = teacherService.addTeacher(teacher);
            if(i>=1){
                return AjaxResult.success();
            }
            throw new BaseException("添加失败, 数据库错误！");
        }
        throw new BaseException("添加失败,参数错误！");
    }
    @DeleteMapping
    public AjaxResult deleteTeacher(@RequestBody Integer[] ids){
        if(StringUtils.isNotNull(ids)&&StringUtils.isNotEmpty(ids))
        {
            int i = teacherService.deleteTeachers(ids);
            if(i>=1)
            {
                return AjaxResult.success();
            }
            throw new BaseException("删除失败, 数据库错误！");
        }
        throw new BaseException("删除失败,参数错误！");
    }
    @PutMapping
    public AjaxResult updateTeacher(@RequestBody Teacher teacher){
        if(StringUtils.isNotNull(teacher)&&StringUtils.isNotNull(teacher.getId()))
        {
            int i = teacherService.updateTeacherById(teacher);
            if(i>=1){
                return AjaxResult.success();
            }
            throw new BaseException("更新失败, 数据库错误！");
        }
        throw new BaseException("更新失败,参数错误！");
    }
    @GetMapping("/" +"{id}")
    public AjaxResult getTeacherById(@PathVariable("id") Integer id){
        Teacher teacherById = teacherService.findTeacherById(id);
        if(StringUtils.isNotNull(teacherById))
        {
            return AjaxResult.success(teacherById);
        }
        throw new BaseException("查询失败,数据库错误！");
    }
    @PostMapping("/reset")
    public AjaxResult resetPassword(@RequestBody Teacher teacher){
        Integer integer = teacherService.resetPassword(teacher.getId(), teacher.getPassword());
        if(integer==1)
        return AjaxResult.success();
        throw new BaseException("重置密码失败！");
    }
}

